package server_http

import (
	"context"
	"gitee.com/livo/localfile/controller"
	_ "gitee.com/livo/localfile/docs"
	"gitee.com/livo/localfile/service"
	rice "github.com/GeertJohan/go.rice"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"log"
	"net/http"
	"strconv"
	"time"
)

func InitHttp(ctx context.Context, s *service.Service, port int) (shutDown func(waitSec time.Duration) error) {
	gin.SetMode(gin.DebugMode)
	engine := gin.New()
	// cors
	config := cors.DefaultConfig()
	config.AllowAllOrigins = true
	config.AddAllowHeaders("Content-Type", "Content-Length", "Authorization", "Accept", "X-Requested-With")
	config.AddAllowMethods("PUT", "POST", "GET", "DELETE", "OPTIONS")
	engine.Use(cors.New(config))
	// hello
	engine.GET("/hello", func(c *gin.Context) {
		c.JSON(200, "hello")
	})
	// swagger + gzip压缩
	engine.GET("/swagger/*any", gzip.Gzip(gzip.DefaultCompression), ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 静态文件
	fileRouter := engine.Group("")
	fileRouter.StaticFS("/files", gin.Dir(".", true))

	// api 服务
	apiRouter := engine.Group("/api")
	fileCtl := &controller.FileController{Service: s}
	apiRouter.GET("/file/get_file_list", fileCtl.GetFileList)

	// 静态网页
	fileRouter.Use(gzip.Gzip(gzip.DefaultCompression))
	fileRouter.StaticFS("/web", rice.MustFindBox("../web/build").HTTPBox())
	fileRouter.GET("/", func(c *gin.Context) {
		c.Redirect(302, "/web/index.html")
	})

	// 开始服务
	srv := &http.Server{
		Addr:    ":" + strconv.Itoa(port),
		Handler: engine,
	}
	//是否有ssl.public_key ssl.private_key
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			log.Println(err)
			return
		}
	}()
	return func(waitSec time.Duration) error {
		ctxTimeout, cancelFunc := context.WithTimeout(ctx, waitSec)
		defer cancelFunc()
		// shutdown
		err := srv.Shutdown(ctxTimeout)
		if err != nil {
			log.Println(err)
			return err
		} else {
			log.Println("end of service...")
			return nil
		}
	}
}
